package com.etc.bridgedataanalysis.service;

import com.etc.utils.DateUtils;
import com.etc.utils.UUIDUtil;

import java.io.FileNotFoundException;
import java.sql.*;
import java.text.ParseException;
import java.util.Calendar;


/**
 * @Main
 * @Author zsw
 * @Date 2019/12/11 17:40
 **/
public class Bridge {

    private static Connection con;
    private static Statement sta;
    private static ResultSet rs;


    /********************静态块可以提高效率***********/
    static {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 加载驱动程序
     */

    public static Connection getConnection() {

        String url = "jdbc:sqlserver://localhost:1433;DatabaseName=FiberData";
        try {
            con = DriverManager.getConnection(url, "sa", "123456");
            sta = con.createStatement();
            System.out.println("连接成功");

        } catch (SQLException e) {
            System.out.println("连接失败");
            e.printStackTrace();
        }

        return con;
    }

    public static void insert(String filePath) throws ParseException, SQLException, FileNotFoundException {

        String[] directoryName = filePath.split("\\\\");
        String[] pictureName = directoryName[6].split("_");
        //获取当前时间
        //添加入库时间到bizVehicle对象中
        Calendar date = Calendar.getInstance();

        String tableName = "biz_vehicle" + "_" + (date.get(Calendar.MONTH)+1);

        String sql = "insert into " + tableName +"(id,create_date,insert_date,ip_address,speed,type,veh_plate) values (?,?,?,?,?,?,?)";

        PreparedStatement prepareStatement = getConnection().prepareStatement(sql);
        prepareStatement.setString(1, UUIDUtil.getUUID().replaceAll("-",""));
        prepareStatement.setDate(2,new Date(Long.valueOf(DateUtils.fromatString(pictureName[4]))));
        prepareStatement.setDate(3,new Date(System.currentTimeMillis()));
        prepareStatement.setString(4,directoryName[2]);
        prepareStatement.setString(5,pictureName[0]);
        prepareStatement.setString(6,pictureName[1]);
        prepareStatement.setString(7,pictureName[6]);

        int i = prepareStatement.executeUpdate();


        System.out.println(i == 0? "添加"+ tableName +"表数据失败":"添加"+ tableName +"表数据成功");

    }
}
